/*
 * Licensed to the http://code.google.com/p/crunchutils under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crunchutils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A set of utility methods to work with files and directories
 * @author James Selvakumar
 */
public class CrunchFileUtils
{
    private static final Logger logger = LoggerFactory.getLogger(CrunchFileUtils.class);

    /**
     * Appends the text to a file
     * @param file
     * @param text
     */
    public static void appendStringToFile(File file, String text)
    {
        BufferedWriter writer = null;
        try {
            createParentDir(file);
            writer = new BufferedWriter(new FileWriter(file, true));
            writer.write(text);
            writer.newLine();
            writer.flush();
        } catch (IOException ex) {
            logger.error("Error occured while appending the text " + text + " to the file " + file);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    /**
     * Creates parent directory for a file if it does not exist
     * @param file
     */
    public static void createParentDir(File file)
    {
        createDirIfNotExists(file.getParentFile());
    }

    /**
     * Creates a directory if it doesn not exist
     * @param dir
     */
    public static void createDirIfNotExists(File dir)
    {
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * Replaces the file's actual extension with the given extension.<br/>
     * NOTE: This method doesn't actually renames the file
     * <p>
     * For example, <br/>
     * <pre>
     *  File file1 = new File("file.txt");
     *  File fileWithNewExtension = CrunchFileUtils.substituteExtension()
     * </pre>
     * </p>
     * @param file file
     * @param newExtension the new extension
     * @return a new file object with the replaced extension
     */
    public static File replaceExtension(File file, String newExtension)
    {
        String originalExtension = FilenameUtils.getExtension(file.getName());
        String originalFile = file.getPath();
        return new File(originalFile.replaceAll(originalExtension, newExtension));
    }

    /**
     * A null safe approach to check whether the given file exists or not.
     * If a null value is passed, the method will return false;
     * @param file the file to be checked
     * @return true if file exists; false otherwise
     */
    public static boolean isExists(File file)
    {
        return file != null && file.exists() ? true : false;
    }
}
